package ru.sgu.codecenter.fidx.command;

import ru.sgu.codecenter.fidx.model.HelpItem;
import ru.sgu.codecenter.fidx.model.IndexInserter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class UpdateCommand extends Command {
    private IndexInserter indexInserter;

    @Override
    public String getName() {
        return "update";
    }

    @Override
    public List<HelpItem> getHelpItems() {
        List<HelpItem> helpItems = new ArrayList<HelpItem>();
        helpItems.add(new HelpItem(getName() + " <file or directory>", "update file or directory in the index with whole subtree"));
        return helpItems;
    }

    @Override
    public void execute(String[] args) {
        DeleteCommand deleteCommand = new DeleteCommand();
        deleteCommand.setEngine(engine);
        indexInserter = new IndexInserter(engine);
        for (String arg : args) {
            deleteCommand.deleteDirectory(new File(arg));
            updateFileOrDirectory(new File(arg));
        }

        indexInserter.stop();
    }

    private void updateFileOrDirectory(File file) {
        if (!file.exists()) {
            warn("Can't find file \"" + file + "\".");
            return;
        }

        if (file.isFile()) {
            updateFile(file);
            return;
        }

        if (file.isDirectory()) {
            updateDirectory(file);
            return;
        }

        warn("The path \"" + file + "\" is nether file nor directory.");
    }

    private void updateFile(File file) {
        indexInserter.insert(file);
    }

    void updateDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                updateFileOrDirectory(file);
            }
        }
    }
}
